﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.Management.Automation.Runspaces;
using System.IO;

namespace CorrelationIdPage
{
    class CorrelationQuery
    {
        Collection<string[]> _results;
        private string _savePath, _mergeCommand;

        public DateTime StartDateTime
        {
            get;
            set;
        }
        public DateTime EndDateTime
        {
            get;
            set;
        }
        public String CorrelationID
        {
            get;
            set;
        }
        public String SavePath
        {
            get { return _savePath; }
        }
        public String MergeCommand
        {
            get { return _mergeCommand; }
        }
        public QueryResult Result
        {
            get { return new QueryResult(_results); }
        }

        public CorrelationQuery(DateTime startDateTime, DateTime endDateTime, string correlationID)
        {
            StartDateTime = startDateTime;
            EndDateTime = endDateTime;
            CorrelationID = correlationID;
            _results = new Collection<string[]>();
        }
        public void QueryServers()
        {
            _savePath = String.Format("{0}{1}.log", Path.GetTempPath(), System.Guid.NewGuid().ToString());
            _mergeCommand = String.Format("Merge-SPLogFile -OverWrite -Path '{0}' -StartTime '{1}' -EndTime '{2}' -Correlation '{3}'", _savePath, StartDateTime, EndDateTime, CorrelationID);

            InitialSessionState iss = InitialSessionState.CreateDefault();
            PSSnapInException warning;
            iss.ImportPSSnapIn("Microsoft.SharePoint.PowerShell", out warning);
            Runspace runspace = RunspaceFactory.CreateRunspace(iss);
            runspace.Open();
            Pipeline pipeline = runspace.CreatePipeline();
            pipeline.Commands.AddScript(_mergeCommand);
            try
            {
                pipeline.Invoke();
            }
            catch (Exception ex)
            {
                File.Delete(_savePath);
                throw ex;
            }

            if (File.Exists(_savePath))
            {
                StreamReader sReader = new StreamReader(_savePath);
                string inputLine = "";

                string[] values = null;
                while ((inputLine = sReader.ReadLine()) != null)
                {
                    values = inputLine.Split('\t');
                    _results.Add(values);
                }
                sReader.Close();
            }
            else
            {
                throw new FileNotFoundException("No results were found.");
            }

            runspace.Close();
            File.Delete(_savePath);
        }
    }
}
